var supplierObj = [];
var limit = 30;var clockTime = 60; var todoTimer;
var tid, itemIndex = 9,strengthId=-1,expendId=-1,conId=-1;
var strengthObj = new Object(),snMaterialObj = new Object(),cjMaterialObj = new Object(),pzMaterialObj = new Object(),
    xjMaterialObj = new Object(),chMaterialObj = new Object(),sMaterialObj = new Object(),wjMaterialObj = new Object(),
    materialObj = new Object(),strengthObj = new Array(),levelOptimizeObj = new Object();
var materialTypeObj = convertEnumToObj(materialTypeList);
var proTypeObj = convertEnumToObj(proTypeList);
var materialArray = new Array(),controlArray = new Array(), lineArray = new Array(),lineTabId = -1;//材料添加列表
var snHtml='<option value="">请选择水泥材料</option>',xjHtml='<option value="">请选择细集料</option>',
    cjHtml='<option value="">请选择粗集料</option>',sHtml='<option value="">请选择水</option>',
    chHtml='<option value="">请选择掺和料</option>',wjHtml='<option value="">请选择外加剂</option>',
    pzHtml='<option value="">请选择配重材料</option>',mtHtml = '<option value="">请选择材料类型</option>',
    allHtml = '<option value="">请选择材料</option>',constructHtml = '<option value="">请选择生产配合比</option>',
    historyHtml = '<option value="">请选择历史配合比</option>';
// refreshTimer(clockTime);
// function refreshTimer(time) {//定时器刷新工控仓位关联信息
//     time--;
//     if (time <= 0) {
//         time = clockTime;
//         clearTimeout(todoTimer);
//         var option = {orgId:$('.search-origin').val(),limit:10000,curr:1};
//         loadInitData(JSON.stringify(option),'/system/storage/match/page', 2,'application/json');
//         refreshTimer(time);
//     } else {
//         todoTimer = setTimeout('refreshTimer(' + time +')',1000);
//     }
// }
layui.use(['laypage', 'table', 'form', 'laydate'], function(){
    var table = layui.table,laydate = layui.laydate,util = layui.util,form = layui.form,element = layui.element;;
    $.each(materialTypeList, function (index, val) {
        mtHtml += '<option value="' + val.id + '">' + val.name + '</option>';
    });
    $.each(strengthList, function (index, val) {
        strengthObj[val.id] = val;
    });
    $.each(materialList, function (index, val) {
        materialObj[val.id] = val;
        var norms = val.fullName;
        if (!isNull(val.brand)) {
            norms += '(' + val.brand + ')';
        }
        if (val.type == 2){//水泥
            snMaterialObj[val.id] = val;
            snHtml +='<option value="' + val.id + '">' + norms + '</option>';
        }else if (val.type == 3){//细集料
            xjMaterialObj[val.id] = val;
            xjHtml +='<option value="' + val.id + '">' + norms + '</option>';
        }else if (val.type == 4){//粗集料
            cjMaterialObj[val.id] = val;
            cjHtml +='<option value="' + val.id + '">' + norms + '</option>';
        }else if (val.type == 5){//掺和料
            chMaterialObj[val.id] = val;
            chHtml +='<option value="' + val.id + '">' + norms + '</option>';
        }else if (val.type == 6){//外加剂
            wjMaterialObj[val.id] = val;
            wjHtml +='<option value="' + val.id + '">' + norms + '</option>';
        }else if (val.type == 7){//水
            sMaterialObj[val.id] = val;
            sHtml +='<option value="' + val.id + '">' + norms + '</option>';
        }else if (val.type == 9) {//配重材料
            pzMaterialObj[val.id] = val;
            pzHtml +='<option value="' + val.id + '">' + norms + '</option>';
        }
        allHtml +='<option value="' + val.id + '">' + norms + '</option>';
    });
    setTimeout(function () {
        // init();
        var option = {orgId:$('.search-origin').val(),limit:10000,curr:1};
        loadData(JSON.stringify(option),'/system/storage/match/page', 2,'application/json');
    }, 300);

    laydate.render({
        elem: '#add-inspectionDate',
        type: 'datetime',
        done: function(value, date, endDate){
            // console.log(value); // 日期字符，如： 2017-08-18
            // console.log(date); // 包含年月日时分秒各项值的对象
            // console.log(endDate); // 结束日期时间对象，当设置 range 时才会返回。对象成员同上。
        }
    });
    laydate.render({
        elem: '#add-takeEffectDate',
        type: 'datetime',
        done: function(value, date, endDate){

        }
    });
    laydate.render({
        elem: '#search-startTime',
        type: 'datetime',
        done: function(value, date, endDate){

        }
    });
    laydate.render({
        elem: '#search-endTime',
        type: 'datetime',
        done: function(value, date, endDate){

        }
    });

    let todoCols = [
        [
            {field: 'id', title: '标识', width:80, align: 'center', hide: true}
            ,{field: 'code', title: '任务单号', width:160, align: 'center',sort:true}
            ,{field: 'conName', title: '工程名称', width:220, align: 'center',sort:true,templet: function (val) {
                if (isNull(val.conName)) {
                    return "";
                }
                return '<div style="white-space: pre-wrap;">' + val.conName + '</div>';
            }}
            ,{field: 'site', title: '施工部位', width: 160, align: 'center',sort:true,templet: function (val) {
                if (isNull(val.site)) {
                    return "";
                }
                return '<div style="white-space: pre-wrap;">' + val.site + '</div>';
            }}
            ,{field: 'type', title: '状态', width:80, align: 'center',sort:true, templet:function (val){
                var type = val.type;
                if (type != null) {
                    var proType = proTypeObj[type];
                    if (type == 2 || type == 3) {
                        return '<label style="color: #dc322f;">' + proType + '</label>'
                    }
                    return proType;
                }
                return '';
            }}
            ,{field: 'strengthName', title: '强度等级', width:100, align: 'center',sort:true}
            ,{field: 'tech', title: '特性', width:100, align: 'center',sort:true}
            ,{field: 'lineCode', title: '配比保存状态', width:140, align: 'center', templet:function (val) {
                var lineCode_ = val.lineCode;
                if (lineCode_ != null) {
                    var lineCode = lineCode_.split(',');
                    if (lineCode != null && lineCode_.length > 0) {
                        var str = '';
                        $.each(lineCode, function (i, v) {
                            str += '<a href="javascript:void(0)" class="layui-btn layui-btn-sm layui-btn-xs" style="background: #009688;">' + v + '</a>';
                        });
                        return  str;
                    }
                }
                return '';
            }}
            ,{field: 'lineCode', title: '配比上传状态', width:140, align: 'center', templet:function (val) {
                var isUpload_ = val.isUpload;
                var lineCode_ = val.lineCode;
                if (lineCode_ != null) {
                    var lineCode = lineCode_.split(',');
                    var isUpload = isUpload_.split(',');
                    if (lineCode != null && lineCode_.length > 0) {
                        var str = '';
                        $.each(lineCode, function (i, v) {
                            if (isUpload != null) {
                                if (isUpload[i] == 1)
                                    str += '<a href="javascript:void(0)" class="layui-btn layui-btn-sm layui-btn-xs" style="background: #009688;">' + v + '</a>';
                                else
                                    str += '<a href="javascript:void(0)" class="layui-btn layui-btn-sm layui-btn-xs" style="background: #ff5722;">' + v + '</a>';
                            }
                        });
                        return  str;
                    }
                }
                return '';
            }}
            ,{field: 'labCode', title: '配比编号', width:160, align: 'center',sort:true,templet: function (val) {
                if (isNull(val.labCode)) {
                    return "";
                }
                return '<div style="white-space: pre-wrap;">' + val.labCode + '</div>';
            }}
            ,{field: 'distance', title: '运距', width:80, align: 'center',sort:true}
            ,{field: 'castModelName', title: '浇筑方式', width:100, align: 'center',sort:true}
            ,{field: 'clientName', title: '客户名称', width: 160, align: 'center',sort:true}
            ,{field: 'slumps', title: '坍落度', width:90, align: 'center',sort:true}
            ,{field: 'dispatchStartTime', title: '计划开盘时间', width:130, align: 'center',sort:true}
            ,{field: 'actualStartTime', title: '实际开盘时间', width:130, align: 'center',sort:true}
            ,{field: 'planStere', title: '计划方量', width:90, align: 'center',sort:true}
            ,{field: 'sendStere', title: '累计发货', width:90, align: 'center',sort:true}
            ,{field: 'conCode', title: '合同编号', width:140, align: 'center'}
            ,{field: 'status', title: '状态', width:80, align: 'center', templet:function (val) {
                if (val.status == 0)
                    return '启用';
                else
                    return '禁用';
            }}
            ,{field: 'remark', title: '备注', width: 200, align: 'center'}
            ,{fixed: 'right', title:'操作', width: 120, align:'center', templet:function (val) {
                var str = '<a lay-event="upload" href="javascript:void(0)" class="layui-btn layui-btn-xs">上传配比</a>';
                return str;
            }}
        ]
    ];
    let batchCols = [
        [
            {type: 'checkbox'},
            {field: 'id', title: '标识', width:80, align: 'center', hide: true}
            ,{field: 'code', title: '任务单号', width:160, align: 'center',sort:true}
            ,{field: 'conName', title: '工程名称', width:220, align: 'center',sort:true,templet: function (val) {
                if (isNull(val.conName)) {
                    return "";
                }
                return '<div style="white-space: pre-wrap;">' + val.conName + '</div>';
            }}
            ,{field: 'site', title: '施工部位', width: 160, align: 'center',sort:true,templet: function (val) {
                if (isNull(val.site)) {
                    return "";
                }
                return '<div style="white-space: pre-wrap;">' + val.site + '</div>';
            }}
            ,{field: 'type', title: '状态', width:80, align: 'center',sort:true, templet:function (val){
                var type = val.type;
                if (type != null) {
                    var proType = proTypeObj[type];
                    if (type == 2 || type == 3) {
                        return '<label style="color: #dc322f;">' + proType + '</label>'
                    }
                    return proType;
                }
                return '';
            }}
            ,{field: 'strengthName', title: '强度等级', width:100, align: 'center',sort:true}
            ,{field: 'tech', title: '特性', width:100, align: 'center',sort:true}
            ,{field: 'lineCode', title: '配比保存状态', width:140, align: 'center', templet:function (val) {
                var lineCode_ = val.lineCode;
                if (lineCode_ != null) {
                    var lineCode = lineCode_.split(',');
                    if (lineCode != null && lineCode_.length > 0) {
                        var str = '';
                        $.each(lineCode, function (i, v) {
                            str += '<a href="javascript:void(0)" class="layui-btn layui-btn-sm layui-btn-xs" style="background: #009688;">' + v + '</a>';
                        });
                        return  str;
                    }
                }
                return '';
            }}
            ,{field: 'lineCode', title: '配比上传状态', width:140, align: 'center', templet:function (val) {
                var isUpload_ = val.isUpload;
                var lineCode_ = val.lineCode;
                if (lineCode_ != null) {
                    var lineCode = lineCode_.split(',');
                    var isUpload = isUpload_.split(',');
                    if (lineCode != null && lineCode_.length > 0) {
                        var str = '';
                        $.each(lineCode, function (i, v) {
                            if (isUpload != null) {
                                if (isUpload[i] == 1)
                                    str += '<a href="javascript:void(0)" class="layui-btn layui-btn-sm layui-btn-xs" style="background: #009688;">' + v + '</a>';
                                else
                                    str += '<a href="javascript:void(0)" class="layui-btn layui-btn-sm layui-btn-xs" style="background: #ff5722;">' + v + '</a>';
                            }
                        });
                        return  str;
                    }
                }
                return '';
            }}
            ,{field: 'labCode', title: '配比编号', width:160, align: 'center',sort:true,templet: function (val) {
                if (isNull(val.labCode)) {
                    return "";
                }
                return '<div style="white-space: pre-wrap;">' + val.labCode + '</div>';
            }}
            ,{field: 'distance', title: '运距', width:80, align: 'center',sort:true}
            ,{field: 'castModelName', title: '浇筑方式', width:100, align: 'center',sort:true}
            ,{field: 'clientName', title: '客户名称', width: 140, align: 'center',sort:true}
            ,{field: 'slumps', title: '坍落度', width:90, align: 'center',sort:true}
            ,{field: 'dispatchStartTime', title: '计划开盘时间', width:130, align: 'center',sort:true}
            ,{field: 'actualStartTime', title: '实际开盘时间', width:130, align: 'center',sort:true}
            ,{field: 'planStere', title: '计划方量', width:90, align: 'center',sort:true}
            ,{field: 'sendStere', title: '累计发货', width:90, align: 'center',sort:true}
            ,{field: 'conCode', title: '合同编号', width:140, align: 'center'}
            ,{field: 'status', title: '状态', width:80, align: 'center', templet:function (val) {
                if (val.status == 0)
                    return '启用';
                else
                    return '禁用';
            }}
            ,{field: 'remark', title: '备注', width: 100, align: 'center'}
            // ,{fixed: 'right', title:'操作', width: 120, align:'center', templet:function (val) {
            //     var str = '<a lay-event="upload" href="javascript:void(0)" class="layui-btn layui-btn-xs">上传配比</a>';
            //     return str;
            // }}
        ]
    ];
    table.render({
        elem: '#body-list'
        ,url: '/lab/expend-upload/page'
        ,method: 'post'
        ,page: true
        ,cols: todoCols
        ,limit: limit
        ,height:800
        ,limits: [30,50,100]
        ,request: {
            pageName: 'curr' //页码的参数名称，默认：page
            ,limitName: 'limit' //每页数据量的参数名，默认：limit
        }
        ,where: {
            offset: 0,
            limit: limit
        }
        ,parseData: function(res){ //res 即为原始返回的数据
            console.log(res)
            if (res.code == 0 && res.data != null) {
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.records //解析数据列表
                };
            } else {
                return {
                    "code": res.code, //解析接口状态
                    "msg": '没有任何数据', //解析提示文本
                    "count": 0, //解析数据长度
                    "data": '' //解析数据列表
                };
            }
        }
    });

    //监听行工具事件
    table.on('tool(body-list)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
        var data = obj.data //获得当前行数据
            ,layEvent = obj.event; //获得 lay-event 对应的值
        if(layEvent === 'upload'){
            tid = data.id;
            conId = data.conId;
            updateWindow(data);
            form.render(data);
        }
    });
    table.on('rowDouble(body-list)', function(obj){
        var data = obj.data;
        tid = data.id;
        conId = data.conId;
        updateWindow(data);
    });
    form.on('select(add-materialType)', function(data) {//操作下拉选择框信息
        var elem = data.elem;
        var index = $(elem).attr('data-value');
        if (data.value != null) {
            buildItemMaterial(data.value, index, lineTabId);
            $('.line-tab' + lineTabId).find('.uploadBtns' + lineTabId).attr('data-flag', 1);
            $('.line-tab' + lineTabId).find('.addBtns' + lineTabId).attr('data-flag', 1);
        }
    });
    form.on('select(add-material)', function(data) {//操作下拉选择框信息
        var elem = data.elem;
        var index = $(elem).attr('data-value');
        if (data.value != null) {
            buildItemControl(data.value, index, lineTabId, -1);//组装子项的erp仓位、工控仓位信息
            $('.line-tab' + lineTabId).find('.uploadBtns' + lineTabId).attr('data-flag', 1);
            $('.line-tab' + lineTabId).find('.addBtns' + lineTabId).attr('data-flag', 1);
        }
    });
    form.on('select(add-storage)', function(data) {//操作下拉选择框信息
        if (data.value != null) {
            $('.line-tab' + lineTabId).find('.uploadBtns' + lineTabId).attr('data-flag', 1);
            $('.line-tab' + lineTabId).find('.addBtns' + lineTabId).attr('data-flag', 1);
            var index_ = $(data.elem).attr('data-value');
            var controlStorage = $('.line-tab' + lineTabId).find('.add-storage' + index_).find("option:selected").attr('data-controlStorage');
            var controlId = $('.line-tab' + lineTabId).find('.add-storage' + index_).find("option:selected").attr('data-controlId');
            $('.line-tab' + lineTabId).find('.add-control' + index_).val(controlStorage);
            $('.line-tab' + lineTabId).find('.add-control' + index_).attr('data-id', controlId);
        }
    });
    form.on('select(add-construct)', function(data) {//操作下拉选择框信息
        var elem = data.elem;
        var optimizecode = $(elem).find("option:selected").attr('data-optimizecode');
        var time = $(elem).find("option:selected").attr('data-time');
        var mixTime = $(elem).find("option:selected").attr('data-mixTime');
        var optimizeid = $(elem).find("option:selected").attr('data-optimizeid');
        var index_ = $(data.elem).attr('data-value');
        var sumDosage = $(elem).find("option:selected").attr('data-sumDosage');
        var minDosage = $(elem).find("option:selected").attr('data-minDosage');
        var maxDosage = $(elem).find("option:selected").attr('data-maxDosage');
        $('.line-tab' + lineTabId).find('.add-sumDosage' + index_).val(sumDosage);
        $('.line-tab' + lineTabId).find('.add-minDosage' + index_).val(minDosage);
        $('.line-tab' + lineTabId).find('.add-maxDosage' + index_).val(maxDosage);
        if (data.value != null) {//加载配合比材料详情
            loadMaterial({constructId:data.value}, '/lab/expend-upload/find-construct', lineTabId, 0);
        }
        if (optimizecode != null) {
            var data = {optimizeid:optimizeid,optimizecode:optimizecode,time:time,mixTime:mixTime}
            buildOptimize(data);//组装优化配比数据
        }
    });
    form.on('select(add-historyConstruct)', function(data) {//操作下拉选择框信息
        var elem = data.elem;
        var constructId = $(elem).find("option:selected").attr('data-constructId');
        var optimizecode = $(elem).find("option:selected").attr('data-optimizecode');
        var time = $(elem).find("option:selected").attr('data-time');
        var mixTime = $(elem).find("option:selected").attr('data-mixTime');
        var optimizeid = $(elem).find("option:selected").attr('data-optimizeid');
        var index_ = $(data.elem).attr('data-value');
        var sumDosage = $(elem).find("option:selected").attr('data-sumDosage');
        var minDosage = $(elem).find("option:selected").attr('data-minDosage');
        var maxDosage = $(elem).find("option:selected").attr('data-maxDosage');
        $('.line-tab' + lineTabId).find('.add-construct' + index_).val(constructId);
        $('.line-tab' + lineTabId).find('.add-sumDosage' + index_).val(sumDosage);
        $('.line-tab' + lineTabId).find('.add-minDosage' + index_).val(minDosage);
        $('.line-tab' + lineTabId).find('.add-maxDosage' + index_).val(maxDosage);
        form.render();
        if (data.value != null) {//加载配合比材料详情
            loadMaterial({uploadId:data.value}, '/lab/expend-upload/find-expend', lineTabId, 0);
        }
        if (optimizecode != null) {
            var data = {optimizeid:optimizeid,optimizecode:optimizecode,time:time,mixTime:mixTime}
            buildOptimize(data);//组装优化配比数据
        }
    });
    form.on('checkbox(line-checkbox)', function(data) {
        var elem = data.elem; // 获得 checkbox 原始 DOM 对象
        var checked = elem.checked; // 获得 checkbox 选中状态
        var code = $(elem).attr('data-code');
        var id = $(elem).attr('data-id');
        if (checked == true) {
            var html = buildMaterialTabHtml(id, code, -1);
            element.tabAdd('tab-line', {
                title: code,
                content: html,
                id: id, // 实际使用一般是规定好的id，这里以毫秒数模拟
                change: true // 是否添加完毕后即自动切换
            });
            lineTabId = id;
            lineArray.push(id);
            element.tabChange('tab-line', id); //切换到：选择tab
            $('.add-construct' + id).html(constructHtml);
            // $('.add-historyConstruct' + id).html(historyHtml);
            setTimeout(function () {
                var strengthId = $('.addModal .add-strengthName').attr('data-id');
                var options = {strengthId:strengthId,lineId:id,
                    historyId:'add-historyConstruct' + id};
                loadData(options,'/lab/expend-upload/find-history-v1', 4);
            }, 100);
        } else {
            element.tabDelete('tab-line', id);
            $.each(lineArray, function (i, val) {
                if (val != null) {
                    if (val == id) {
                        expendId = -1;
                        lineArray.splice(i, 1);
                    }
                }
            });
        }
        form.render();
    });
    element.on('tab(tab-line)', function(data){//tab选项卡切换事件
        // console.log(data.index + '   ' + $(this).attr('lay-id') + $(this).html()); // 得到当前的 tab ID
        lineTabId = $(this).attr('lay-id');
        var materialItem = $('.line-tab' + lineTabId).find('.material-item');
        materialArray = new Array();//重置材料子项下标
        if (materialItem != null) {
            $.each(materialItem, function (i, v) {
                materialArray.push($(v).attr('data-index'));
            });
        }
    });
    form.on('select(search-proType)', function(data) {
        $(".btn-query").trigger("click");
    });
    form.on('select(search-uploadType)', function(data) {
        $(".btn-query").trigger("click");
    });
    $('.btn-batch-update').on('click', function () {//点击批量上传信息
        var checkStatus = table.checkStatus('batch-body-list');
        var checkData = checkStatus.data;
        if (checkData == null || checkData.length == 0) {
            layer.msg('请选择需要上传的任务单~！');
            return ;
        }
        var lineIds = '';
        var indentId = $('.addModal .add-indentCode').attr('data-id');
        var strengthId = $('.addModal .add-strengthName').attr('data-id');
        if (indentId == null) {
            layer.msg('没有选中生产线~！');
            return ;
        }
        $.each(lineArray, function (i, val) {
            if (val != null) {
                lineIds += val + ','
            }
        });
        var uploadIndentIds = '';
        $.each(checkData, function (index, val) {
            if (val != null) {
                uploadIndentIds += val.id + ','
            }
        });
        layer.confirm('确认是否批量上传已选择任务单的配合比信息', {
            btn: ['确定', '取消']
        }, function(index, layero){
            var options = {lineIds:lineIds,indentId:indentId,uploadIndentIds:uploadIndentIds,
                strengthId:strengthId,page:1,limit:limit};
            layer.closeAll();
            save(options, '/lab/expend-upload/upload-batch', 2,'application/x-www-form-urlencoded');
        });
    });
    $('.addModal').on('keyup','.value-set-key', function () {
        validateMealStandard(this);
        var index = $(this).attr('data-value');
        if (index != null) {
            var constructNum = convertNumber($('.material-body-list' + lineTabId).find('.add-constructNum' + index).val());
            var dosage = convertNumber($('.material-body-list' + lineTabId).find('.add-dosage' + index).val());
            var realDosage = parseFloat(dosage) + parseFloat(constructNum);
            if (realDosage < 0)
                realDosage = 0;
            $('.material-body-list' + lineTabId).find('.add-realDosage' + index).val(parseFloat(realDosage).toFixed(2));
        }
        $('.line-tab' + lineTabId).find('.addBtns' + index).attr('data-flag', 1);
        $('.line-tab' + lineTabId).find('.uploadBtns' + index).attr('data-flag', 1);
        $('.line-tab' + lineTabId).find('.uploadOrSaveBtns' + index).attr('data-flag', 1);
        calcRealSumDosage(lineTabId);//计算实际容重
        $(this).css({'color' : '#cf3618'});
    });
    $('.addModal').on('keyup','.value-set-key1', function () {//实际量、计算量按键实际
        validateMealStandard(this);
        var index = $(this).attr('data-value');
        if (index != null) {
            var realDosage = $('.material-body-list' + lineTabId).find('.add-realDosage' + index).val();
            var constructNum = convertNumber($('.material-body-list' + lineTabId).find('.add-constructNum' + index).val());
            // var dosage = convertNumber($('.material-body-list' + lineTabId).find('.add-dosage' + index).val());
            var dosage = parseFloat(realDosage) - parseFloat(constructNum);
            $('.material-body-list' + lineTabId).find('.add-dosage' + index).val(parseFloat(dosage).toFixed(2));
        }
        $('.line-tab' + lineTabId).find('.addBtns' + index).attr('data-flag', 1);
        $('.line-tab' + lineTabId).find('.uploadBtns' + index).attr('data-flag', 1);
        $('.line-tab' + lineTabId).find('.uploadOrSaveBtns' + index).attr('data-flag', 1);
        calcRealSumDosage(lineTabId);//计算实际容重
        $(this).css({'color' : '#cf3618'});
    });
    $('.btn-query').on('click', function () {//搜索按钮
        var searchVal = $('.search-text').val();
        var orgId = $('.search-origin').val();
        var proType = $('.search-proType').val();
        var isUpload = $('.search-uploadType').val();
        var startTime = $('.search-startTime').val();
        var endTime = $('.search-endTime').val();
        var option = {page:1,limit:limit};
        if (!isNull(searchVal))
            option['searchVal'] = searchVal;
        if (!isNull(proType))
            option['proType'] = proType;
        if (!isNull(orgId))
            option['orgId'] = orgId;
        if (!isNull(startTime))
            option['startTime'] = startTime;
        if (!isNull(endTime))
            option['endTime'] = endTime;
        if (isUpload != null)
            option['isUpload'] = isUpload;
        // console.log(option)
        table.reload('body-list', {
            where: option,page:{curr:1}
        });
    });

    $('.btn-add').on('click', function () {
        $('.addModal').show();
    });
    $(".addModal .close").on("click", function() {
        closeTab();
    });
    $(".batchModal .close").on("click", function() {
        $('.batchModal').hide();
    });
    $('.layui-tab-content').on('click', '.btn-remove', function () {
        var index_ = $(this).attr('data-value');
        if (index_ != null) {
            layer.confirm('是否需要移除子项~?', {
                btn: ['确定', '取消']
            }, function(index, layero){
                var removeName = 'material-item' + index_;
                // var itemId = $('.material-body-list' + lineTabId).find('.add-used' + index_).attr('data-id');
                $('.material-body-list' + lineTabId).find('.' + removeName).remove();
                form.render();
                layer.close(index);
                $.each(materialArray, function (i, val) {
                    if (val != null) {
                        if (val == index_) {
                            materialArray.splice(i, 1);
                        }
                    }
                });
            });
        }
    });
    $('.layui-tab-content').on('click', '.btn-material-add', function () {//添加材料子项
        var id = $(this).attr('data-id');
        var itemIndex = 0;
        if (materialArray != null && materialArray.length > 0)
            itemIndex = materialArray[materialArray.length - 1];
        itemIndex++;
        var html = buildMaterialItemHtml(itemIndex, 0, {});
        $('.material-body-list' + lineTabId).append(html);
        materialArray.push(itemIndex);
        form.render();
    });

    //点击添加提交
    form.on('submit(addBtns)', function() {
        var flag = $(this).attr('data-flag');
        var uploadId = $(this).attr('data-uploadId');
        var sumDosage = $.trim($('.add-sumDosage' + lineTabId).val());//标号容设计重
        var minDosage = $.trim($('.add-minDosage' + lineTabId).val());//标号下限容设
        var maxDosage = $.trim($('.add-maxDosage' + lineTabId).val());//标号上线容重
        if (sumDosage == null || sumDosage < 200 || minDosage == null || minDosage < 200
            || maxDosage == null || maxDosage < 200) {
            layer.confirm('未设置设计容重、标号下限容重、标号上限容重是否继续操作', function(index){
                // obj.del(); // 删除对应行（tr）的 DOM 结构，并更新缓存
                layer.close(index);
                saveObj(0);
            });
        } else {
            saveObj(0);
        }
    });
    form.on('submit(uploadBtns)', function() {
        var flag = $(this).attr('data-flag');
        var uploadId = $(this).attr('data-uploadId');
        if (flag == 1) {
            layer.msg('配合比有变更,请先保存后再上传');
            return ;
        }
        if (uploadId == null || uploadId < 1) {
            layer.msg('配合比未保存,请先保存后再上传');
            return ;
        }
        var sumDosage = $.trim($('.add-sumDosage' + lineTabId).val());//标号容设计重
        var minDosage = $.trim($('.add-minDosage' + lineTabId).val());//标号下限容设
        var maxDosage = $.trim($('.add-maxDosage' + lineTabId).val());//标号上线容重
        if (sumDosage == null || sumDosage < 200 || minDosage == null || minDosage < 200
            || maxDosage == null || maxDosage < 200) {
            layer.confirm('未设置设计容重、标号下限容重、标号上限容重是否继续操作', function(index){
                // obj.del(); // 删除对应行（tr）的 DOM 结构，并更新缓存
                layer.close(index);
                saveObj(2);
            });
        } else {
            saveObj(2);
        }
    });
    form.on('submit(uploadOrSaveBtns)', function() {
        var sumDosage = $.trim($('.add-sumDosage' + lineTabId).val());//标号容设计重
        var minDosage = $.trim($('.add-minDosage' + lineTabId).val());//标号下限容设
        var maxDosage = $.trim($('.add-maxDosage' + lineTabId).val());//标号上线容重
        if (sumDosage == null || sumDosage < 200 || minDosage == null || minDosage < 200
            || maxDosage == null || maxDosage < 200) {
            layer.confirm('未设置设计容重、标号下限容重、标号上限容重是否继续操作', function(index){
                // obj.del(); // 删除对应行（tr）的 DOM 结构，并更新缓存
                layer.close(index);
                saveObj(1);
            });
        } else {
            saveObj(1);
        }
    });
    form.on('submit(saveBatchBtns)', function() {//集中上传
        if (lineArray == null || lineArray.length == 0) {
            layer.msg('没有选中生产线~！');
            return ;
        }
        var lineIds = '';
        var indentId = $('.addModal .add-indentCode').attr('data-id');
        var strengthId = $('.addModal .add-strengthName').attr('data-id');
        if (indentId == null) {
            layer.msg('没有选中生产线~！');
            return ;
        }
        $.each(lineArray, function (i, val) {
            if (val != null) {
                lineIds += val + ','
            }
        });
        var options = {indentId:indentId,lineIds:lineIds,strengthId:strengthId};
        loadData(options,'/lab/expend-upload/find-batch-line', 5);
    });

    function save(option, url, type, contentType) {//新增或修改
        var loading = layer.load(1);
        $.ajax({
            url: url,
            type: 'put',
            dataType: 'json',
            data:option,
            contentType: contentType,
            timeout: 30000,
            success: function(res) {
                layer.close(loading);
                if(res.code == 0) {
                    if (type == 0) {
                        if (res.msg != null)
                            layer.msg(res.msg);
                        else
                            layer.msg("更新成功!");
                        $(".btn-query").trigger("click");
                        //option.lineId uploadBtns
                        if (res.data != null) {//更新上传配比ID
                            var data = res.data;
                            $('.line-tab' + data.uploadLine).find('.uploadBtns' + data.uploadLine).attr('data-uploadId', data.id);
                            $('.line-tab' + data.uploadLine).find('.uploadBtns' + data.uploadLine).attr('data-flag', 0);
                            $('.line-tab' + data.uploadLine).find('.addBtns' + data.uploadLine).attr('data-uploadId', data.id);
                            $('.line-tab' + data.uploadLine).find('.addBtns' + data.uploadLine).attr('data-flag', 0);
                        }
                        // setTimeout(function () {
                        //     closeTab();
                        //     form.render();
                        // }, 3000);
                    } else if (type == 1) {
                        layer.msg("更新成功!");
                        $('.material-body-list').find('.' + option.removeName).remove();
                        form.render();
                        $.each(materialArray, function (i, val) {
                            if (val != null) {
                                if (val == option.index) {
                                    materialArray.splice(option.index, 1);
                                }
                            }
                        });
                    } else if (type == 2) {
                        if (res.msg != null)
                            layer.msg(res.msg);
                        else
                            layer.msg("更新成功!");
                        table.reload('batch-body-list', {
                            where: option,page:{curr:1}
                        });
                        setTimeout(function () {
                            $(".btn-query").trigger("click");
                        },200);
                    }
                } else {
                    layer.msg(res.msg);
                    return;
                }
            },
            error: function(res) {
                layer.msg("请求失败，请稍后再试！");
                layer.close(loading);
                return;
            },
            complete: function(XMLHttpRequest, status) {
                if(status == 'timeout') {
                    layer.msg("请求超时，请稍后再试！");
                    layer.close(loading);
                    return;
                }
            }
        })
    }
    function loadMaterial(option, url, lineId, type) {
        var loading = layer.load(1);
        $.ajax({
            url: url,
            type: 'post',
            dataType: 'json',
            data:option,
            timeout: 30000,
            success: function(res) {
                layer.close(loading);
                // console.log(res)
                if(res.code == 0 && res.data != null) {
                    var data = res.data;
                    buildMaterialDetailHtml(data, lineId,1);
                } else {
                    layer.msg(res.msg);
                    return;
                }
            },
            error: function(res) {
                layer.msg("请求失败，请稍后再试！");
                layer.close(loading);
                return;
            },
            complete: function(XMLHttpRequest, status) {
                if(status == 'timeout') {
                    layer.msg("请求超时，请稍后再试！");
                    layer.close(loading);
                    return;
                }
            }
        });
    }
    function loadData(option, url, type, contentType) {//加载基础数据 0生产配合比 1历史配合比
        $.ajax({
            url: url,
            type: 'post',
            dataType: 'json',
            data:option,
            timeout: 30000,
            contentType: contentType,
            success: function(res) {
                if (type == 0) {
                    constructHtml = '<option value="">请选择生产配合比</option>';
                } else if (type == 1) {
                    historyHtml = '<option value="">请选择历史配合比</option>'
                }
                if(res.code == 0 && res.data != null) {
                    var data = res.data;
                    if (type == 0 || type == 1) {
                        console.log(res)
                        $.each(data, function (index, val) {
                            var id = val.id;
                            var code = val.code;
                            var strength = val.strength;
                            var optimizecode = val.optimizecode;
                            var showText = code;
                            if (!isNull(optimizecode))
                                showText = code + '[' + optimizecode + ']';
                            var time = val.time;
                            if (type == 0) {
                                constructHtml += '<option value="' + id + '" data-optimizecode="' + optimizecode
                                    + '" data-maxDosage="'+val.maxDosage+'" data-minDosage="'+val.minDosage
                                    +'" data-sumDosage="'+val.volumeWeight+'"  data-time="' + time + '" data-mixTime="'
                                    + val.mixTime + '" data-optimizeid="'
                                    + val.optimizeid + '">' + showText + '</option>';
                            } else if (type == 1) {
                                showText += '[' + time + ']';
                                historyHtml += '<option value="' + id + '" data-optimizecode="' + optimizecode
                                    + '" data-maxDosage="'+val.maxDosage+'" data-minDosage="'+val.minDosage
                                    +'" data-sumDosage="'+val.volumeWeight+'" data-time="' + time + '" data-mixTime="'
                                    + val.mixTime + '" data-optimizeid="'
                                    + val.optimizeid + '">' + showText + '</option>';
                            }
                        });
                    } else if (type == 2) {//查询工控仓位信息
                        data = data.records;
                        $.each(data, function (index, val) {
                            controlArray.push(val);
                        });
                    } else if (type == 3) {
                        var flag = 1;//是否加载材料子项下标
                        $.each(data, function (index, val) {
                            if (index > 0)
                                flag = 0;
                            if (lineArray != null && !lineArray.includes(val.lineId)) {
                                initLineTab(option, val, flag);
                                setTimeout(function () {
                                    console.log(option)
                                    var options = {strengthId:option.strengthId,lineId:val.lineId,
                                        historyId:'add-historyConstruct' + val.lineId};
                                    loadData(options,'/lab/expend-upload/find-history-v1', 4);
                                }, 100);
                            }
                        });
                    } else if (type == 4) {
                        var html = '<option value="">选择历史配比记录</option>';
                        $.each(data, function (index, val) {
                            var id = val.id;
                            var code = val.code;
                            var labLevelCode = val.labLevelCode;
                            var showText = code;
                            if (!isNull(labLevelCode))
                                showText = code + '[' + labLevelCode + ']';
                            var time = val.createTime;
                            html += '<option value="' + id + '" data-maxDosage="'+val.maxDosage+'" data-minDosage="'+val.minDosage
                            +'" data-sumDosage="'+val.dosage+'" data-time="' + time + '" data-mixTime="'
                            + val.mixTime + '" data-constructId="' + val.labLevelConstructId + '" data-optimizeid="'
                            + val.levelOptimizeId + '" data-optimizecode="' + labLevelCode + '">' + showText + '</option>';
                        });
                        if (option.historyId) {
                            $('.' + option.historyId).html(html);
                            form.render();
                        }
                    } else if (type == 5) {
                        $('.batchModal').show();
                        table.render({
                            elem: '#batch-body-list'
                            ,url: '/lab/expend-upload/page'
                            ,method: 'post'
                            ,page: true
                            ,cols: batchCols
                            ,limit: limit
                            ,height:550
                            ,limits: [30,50,100]
                            ,request: {
                                pageName: 'curr' //页码的参数名称，默认：page
                                ,limitName: 'limit' //每页数据量的参数名，默认：limit
                            }
                            ,where: {
                                offset: 0,
                                limit: limit,
                                strengthId:option.strengthId
                            }
                            ,parseData: function(res){ //res 即为原始返回的数据
                                console.log(res)
                                if (res.code == 0 && res.data != null) {
                                    return {
                                        "code": res.code, //解析接口状态
                                        "msg": res.msg, //解析提示文本
                                        "count": res.data.total, //解析数据长度
                                        "data": res.data.records //解析数据列表
                                    };
                                } else {
                                    return {
                                        "code": res.code, //解析接口状态
                                        "msg": '没有任何数据', //解析提示文本
                                        "count": 0, //解析数据长度
                                        "data": '' //解析数据列表
                                    };
                                }
                            }
                        });
                    }
                } else {
                    // layer.msg(res.msg);
                    if (type == 3) {
                        var data = option;
                        $('.addModal').show();
                        $('.addModal .add-indentCode').val(data.code);
                        $('.addModal .add-indentCode').attr('data-id', data.id);
                        $('.addModal .add-strengthName').val(data.strengthName);
                        $('.addModal .add-strengthName').attr('data-id',data.strengthId);
                        $('.addModal .add-clientName').val(data.clientName);
                        $('.addModal .add-site').val(data.site);
                        $('.addModal .add-conName').val(data.conName);
                        $('.addModal .add-distance').val(data.distance);
                        $('.addModal .add-castModelName').val(data.castModelName);
                        $('.addModal .add-receiptUnit').val(data.receiptUnit);
                        $('.addModal .add-tech').val(data.tech);
                        $('.addModal .add-slumps').val(data.lumps);
                        $('.addModal .add-dispatchStartTime').val(data.dispatchStartTime);
                        $('.addModal .add-remark').val(data.remark);
                        form.render();
                    } else if (type == 5) {
                        layer.msg(res.msg);
                    }
                    return ;
                }
            },
            error: function(res) {
                layer.msg("请求失败，请稍后再试！");
                return ;
            },
            complete: function(XMLHttpRequest, status) {
                if(status == 'timeout') {
                    layer.msg("请求超时，请稍后再试！");
                    return ;
                }
            }
        });
    }
    function updateWindow(data) {
        loadData({strengthId:data.strengthId},'/lab/level-construct/find-strength', 0);//加载生产配合比
        // loadData({indentId:data.id},'/lab/expend-upload/find-indent', 1);//加载历史上传配比
        if (data.uploadLine != null && data.isUpload != null) {
            loadData(data,'/lab/expend-upload/find-upload', 3);
        } else {
            setTimeout(function () {
                $('.addModal').show();
            }, 300);
            $('.addModal .add-indentCode').val(data.code);
            $('.addModal .add-indentCode').attr('data-id', data.id);
            $('.addModal .add-strengthName').val(data.strengthName);
            $('.addModal .add-strengthName').attr('data-id', data.strengthId);
            $('.addModal .add-clientName').val(data.clientName);
            $('.addModal .add-site').val(data.site);
            $('.addModal .add-conName').val(data.conName);
            $('.addModal .add-distance').val(data.distance);
            $('.addModal .add-castModelName').val(data.castModelName);
            $('.addModal .add-receiptUnit').val(data.receiptUnit);
            $('.addModal .add-tech').val(data.tech);
            $('.addModal .add-slumps').val(data.slumps);
            $('.addModal .add-dispatchStartTime').val(data.dispatchStartTime);
            $('.addModal .add-remark').val(data.remark);
            form.render();
        }

    }
    function initLineTab(data, obj, flag) {//动态组装上传配合比tab
        setTimeout(function () {
            $('.addModal').show();
        }, 300);
        $('.addModal .add-indentCode').val(data.code);
        $('.addModal .add-indentCode').attr('data-id', data.id);
        $('.addModal .add-strengthName').val(data.strengthName);
        $('.addModal .add-strengthName').attr('data-id', data.strengthId);
        $('.addModal .add-clientName').val(data.clientName);
        $('.addModal .add-site').val(data.site);
        $('.addModal .add-conName').val(data.conName);
        $('.addModal .add-distance').val(data.distance);
        $('.addModal .add-castModelName').val(data.castModelName);
        $('.addModal .add-receiptUnit').val(data.receiptUnit);
        $('.addModal .add-tech').val(data.tech);
        $('.addModal .add-slumps').val(data.slumps);
        $('.addModal .add-dispatchStartTime').val(data.dispatchStartTime);
        $('.addModal .add-remark').val(data.remark);
        if (obj == null)
            return ;
        var checkBox = $('.checkbox-body').find('input[type="checkbox"]');
        $.each(checkBox, function() {
            var lineId = $(this).attr('data-id');
            var uploadId = -1;
            if (obj.uploadId != null && obj.uploadId > 0)
                uploadId = obj.uploadId;
            if (lineId == obj.lineId) {
                $(this).prop('checked', true);
                var html = buildMaterialTabHtml(obj.lineId, obj.lineId, uploadId);
                element.tabAdd('tab-line', {
                    title: obj.lineCode,
                    content: html,
                    id: obj.lineId,
                    change: true // 是否添加完毕后即自动切换
                });
                if (flag == 1) {
                    lineTabId = obj.lineId;
                    element.tabChange('tab-line', obj.lineId); //切换到：选择tab
                }

                lineArray.push(obj.lineId);
                $('.add-construct' + lineId).html(constructHtml);
                // $('.add-historyConstruct' + obj.lineIds).html(historyHtml);
                $('.add-sumDosage' + obj.lineId).val(obj.sumDosage);
                $('.add-minDosage' + obj.lineId).val(obj.minDosage);
                $('.add-maxDosage' + obj.lineId).val(obj.maxDosage);
                $('.add-optimize' + obj.lineId).val(obj.levelCode);
                $('.add-takeEffectDate' + obj.lineId).val(obj.time);
                form.render();
                $('.add-construct' + lineId).val(obj.constructId);
                form.render();
                buildMaterialDetailHtml(obj.lineData, obj.lineId, flag);
            }
        });
    }
    function buildMaterialDetailHtml(data, lineId, flag) {
        if (flag == 1)
            materialArray = new Array();
        var html = '';
        $.each(data, function (index, val) {
            if (val.materialType != null) {
                var valObj = {};
                if (val.constructNum != null)
                    valObj['constructNum'] = val.constructNum;
                else
                    valObj['constructNum'] = 0;
                if (val.constructNum != null)
                    valObj['constructNum'] = val.constructNum;
                else
                    valObj['constructNum'] = 0;
                if (val.standNum != null)
                    valObj['standNum'] = val.standNum;
                else
                    valObj['standNum'] = 0;
                if (val.rate != null)
                    valObj['rate'] = val.rate;
                else
                    valObj['rate'] = 0;
                if (val.dosage != null)
                    valObj['dosage'] = val.dosage;
                else
                    valObj['realDosage'] = 0;
                if (val.dosage != null)
                    valObj['realDosage'] = val.realDosage;
                else
                    valObj['realDosage'] = 0;
                html += buildMaterialItemHtml(index, val.materialType, valObj);
            }
            if (flag == 1)
                materialArray.push(index);
        });
        itemIndex = data.length;
        $('.material-body-list' + lineId).html(html);
        form.render();
        calcRealSumDosage(lineId);//计算实际容重
        $.each(data, function (index, val) {
            if (val.materialType != null) {
                $('.material-body-list' + lineId).find('.add-materialType' + index).val(val.materialType);
            }
            if (val.materialId != null) {
                $('.material-body-list' + lineId).find('.add-material' + index).val(val.materialId);
            }
        });
        form.render();
        $.each(data, function (index, val) {
            if (val.materialId != null) {
                buildItemControl(val.materialId, index, lineId, val.controlStorageId);
            }
        });
    }
    function buildMaterialTabHtml(lineId, code, uploadId) {
        var html = '<div class="line-tab' + lineId + ' line-body">\n' +
            '<div class="layui-form-item" style="margin-bottom: 5px;">\n' +
            '<div class="layui-inline">\n' +
            '<label class="layui-form-label" style="width: 120px;">生产配比代号</label>\n' +
            '<div class="layui-input-inline" style="width: 330px;">\n' +
            '<select class="add-construct' + lineId + '" data-value="' + lineId + '" lay-search="" lay-filter="add-construct">\n' +
            '<option value="">请选择生产配合比</option>\n' +
            '</select></div></div>\n' +
            '<div class="layui-inline">\n' +
            '<label class="layui-form-label" style="width: 110px;">优化配比代号</label>\n' +
            '<div class="layui-input-inline" style="width: 230px">\n' +
            '<input type="text" readonly class="layui-input add-optimize' + lineId + '" placeholder="优化配比代号">\n' +
            '</div></div>\n' +
            '<div class="layui-inline">\n' +
            '<label class="layui-form-label" style="width: 80px;">启用日期</label>\n' +
            '<div class="layui-input-inline" style="width: 180px">\n' +
            '<input type="text" readonly class="layui-input add-takeEffectDate' + lineId + '" placeholder="启用日期">\n' +
            ' </div><label class="layui-form-label" style="width: 80px;">生产线</label>\n' +
            '<div class="layui-input-inline" style="width: 100px">\n' +
            '<input type="text" readonly value="' + code + '" class="layui-input" placeholder="生产线">\n' +
            ' </div></div><div class="layui-inline">\n' +
            '<label class="layui-form-label" style="width: 80px;">搅拌时间</label>\n' +
            '<div class="layui-input-inline" style="width: 80px">\n' +
            '<input type="text" value="30" class="layui-input add-mixTime' + lineId + '" placeholder="搅拌时间">\n' +
            '</div></div></div>\n' +
            '<div class="layui-form-item" style="margin-bottom: 5px;">\n' +
            ' <div class="layui-inline">\n' +
            '<label class="layui-form-label" style="width: 120px;">历史生产配比</label>\n' +
            '<div class="layui-input-inline" style="width: 360px;">\n' +
            '<select class="add-historyConstruct' + lineId + '" data-value="' + lineId + '" lay-search="" lay-filter="add-historyConstruct">\n' +
            '<option value="">选择历史配合比</option>\n' +
            '</select></div></div>\n' +
            '<div class="layui-inline">\n' +
            '<label class="layui-form-label" style="width: 80px;">实际容重</label>\n' +
            '<div class="layui-input-inline" style="width: 80px">\n' +
            '<input type="text" value="0" class="layui-input add-realSumDosage' + lineId + '" placeholder="实际容重">\n' +
            '</div></div><div class="layui-inline">\n' +
            '<label class="layui-form-label" style="width: 80px;">设计容重</label>\n' +
            '<div class="layui-input-inline" style="width: 80px">\n' +
            '<input type="text" value="0" class="layui-input add-sumDosage' + lineId + '" placeholder="设计容重">\n' +
            '</div></div><div class="layui-inline">\n' +
            '<label class="layui-form-label" style="width: 80px;">下限容重</label>\n' +
            '<div class="layui-input-inline" style="width: 80px">\n' +
            '<input type="text" value="0" class="layui-input add-minDosage' + lineId + '" placeholder="下限容重">\n' +
            '</div></div><div class="layui-inline">\n' +
            '<label class="layui-form-label" style="width: 80px;">上限容重</label>\n' +
            '<div class="layui-input-inline" style="width: 80px">\n' +
            '<input type="text" value="0" class="layui-input add-maxDosage' + lineId + '" placeholder="上限容重">\n' +
            '</div></div></div>\n' +
            '<div class="layui-form-item">\n' +
            '<div class="layui-inline">\n' +
            '<label class="layui-form-label" style="width: 140px;text-align: center;">材料类型</label>\n' +
            '<label class="layui-form-label" style="width: 230px;text-align: center;">材料名称</label>\n' +
            '<label class="layui-form-label" style="width: 110px;text-align: center;">设计用量</label>\n' +
            '<label class="layui-form-label" style="width: 110px;text-align: center;">砂浆用量</label>\n' +
            '<label class="layui-form-label" style="width: 110px;text-align: center;">含水(%)</label>\n' +
            '<label class="layui-form-label" style="width: 110px;text-align: center;">计算用量</label>\n' +
            '<label class="layui-form-label" style="width: 110px;text-align: center;">实际用量</label>\n' +
            '<label class="layui-form-label" style="width: 190px;text-align: center;">ERP仓储位置</label>\n' +
            '<label class="layui-form-label" style="width: 190px;text-align: center;">工控仓储位置</label>\n' +
            '<a href="javascript:void(0)" type="reset" data-id="' + lineId + '" class="layui-btn layui-btn-normal btn-material-add">\n' +
            '<i class="layui-icon">&#xe654;</i>添加材料</a></div></div>\n' +
            '<div class="layui-form material-body-list' + lineId + '"></div>\n' +
            '<div class="layui-form-item" style="text-align: center;">\n' +
            '<div class="">\n' +
            '<a class="layui-btn btn-submit addBtns' + lineId + '" data-uploadId="' + uploadId + '" data-flag="0" lay-submit lay-filter="addBtns">保存配比</a>' +
            '<a class="layui-btn btn-submit uploadBtns' + lineId + '" data-uploadId="' + uploadId + '" data-flag="0" style="background: #FD7E56;" lay-submit lay-filter="uploadBtns">上传配比</a>' +
            '<a class="layui-btn btn-submit uploadOrSaveBtns' + lineId + '" data-flag="0" style="background: #FF5722;" lay-submit lay-filter="uploadOrSaveBtns">保存并上传配比</a>\n' +
            '<a class="layui-btn btn-submit saveBatchBtns' + lineId + '" data-flag="0" style="background: #1E9FFF;" lay-submit lay-filter="saveBatchBtns">集中上传</a>\n' +
            '</div></div></div>';
        return html;
    }
    
    function buildMaterialItemHtml(index, type, data) {//加载动态材料列表
        var materialHtml = convertMaterial(type);
        var constructNum = 0;
        var standNum = 0;
        var rate = 0;
        var dosage = 0;
        if (data.constructNum != null)
            constructNum = data.constructNum;
        if (data.standNum != null)
            standNum = data.standNum;
        if (data.rate != null)
            rate = data.rate;
        if (data.dosage != null)
            dosage = data.dosage;
        var realDosage = constructNum + dosage;
        var html = '<div class="layui-form-item material-item material-item' + index + '" data-index="' + index + '">\n' +
            '<div class="layui-input-inline" style="width: 140px;">\n' +
            '<select class="add-materialType' + index + '" data-value="' + index + '" lay-filter="add-materialType">' + mtHtml + '</select></div>\n' +
            '<div class="layui-input-inline" style="width: 220px;">\n' +
            '<select class="add-material' + index + '" data-value="' + index + '" lay-filter="add-material" lay-search="">' + materialHtml + '</select></div>\n' +
            '<div class="layui-input-inline" style="width: 100px;">\n' +
            '<input type="text" value="' + constructNum + '" class="layui-input value-set-key add-constructNum' + index + '" placeholder="设计用量" data-value="' + index + '">\n' +
            '</div>\n' +
            '<div class="layui-input-inline" style="width: 100px;">\n' +
            '<input type="text" value="'+ standNum + '" class="layui-input value-set-key add-standNum' + index + '" placeholder="砂浆用量" data-value="' + index + '">\n' +
            '</div>\n' +
            '<div class="layui-input-inline" style="width: 100px;">\n' +
            '<input type="text" value="' + rate + '" class="layui-input value-set-key add-rate' + index + '" placeholder="含水(%)">\n' +
            '</div>\n' +
            '<div class="layui-input-inline" style="width: 100px;">\n' +
            '<input type="text" value="' + dosage + '" class="layui-input value-set-key add-dosage' + index + '" placeholder="计算用量" data-value="' + index + '">\n' +
            '</div>\n' +
            '<div class="layui-input-inline" style="width: 100px;">\n' +
            '<input type="text" value="' + realDosage + '" class="layui-input value-set-key1 add-realDosage add-realDosage' + index + '" placeholder="实际用量" data-value="' + index + '">\n' +
            '</div>\n' +
            '<div class="layui-input-inline" style="width: 180px;">\n' +
            '<select class="add-storage' + index + '" data-value="' + index + '" lay-filter="add-storage" lay-search="">\n' +
            '<option value="">请选择ERP仓储位置</option>\n' +
            '</select></div>\n' +
            '<div class="layui-input-inline" style="width: 180px;">\n' +
            '<input type="text" readonly class="layui-input add-control' + index + '" placeholder="工控仓位位置"></div>' +
            '<a href="javascript:void(0)" data-value="' + index + '" class="layui-btn layui-btn-warm btn-remove" lay-filter="btn-edit">\n' +
            '<i class="layui-icon layui-icon-edit"></i>移除</a></div>';
        return html;
    }
    function convertMaterialType(type) {
        var html = '<opiton value="">请先选择材料类型</opiton>';
        $.each(materialTypeList, function (index, val) {
            if (val.id == type){//水泥
                html += '<opiton value="' + val.id + '" selected="selected">' + val.name + '</opiton>';
            }else {
                html += '<opiton value="' + val.id + '">' + val.name + '</opiton>';
            }
        });
        return html;
    }
    function convertMaterial(type) {
        if (type == 2){//水泥
            return snHtml;
        }else if (type == 3){//细集料
            return xjHtml;
        }else if (type == 4){//粗集料
            return cjHtml;
        }else if (type == 5){//掺和料
            return chHtml;
        }else if (type == 6){//外加剂
            return wjHtml;
        }else if (type == 7){//水
            return sHtml;
        }else if (type == 9) {//配重材料
            return pzHtml;
        } else {
            return allHtml; //所有材料
        }
    }
    function buildOptimize(data) {//组装优化配合比信息
        $('.add-optimize' + lineTabId).attr('data-optimizeid', data.optimizeid);
        $('.add-optimize' + lineTabId).val(convertVal(data.optimizecode));
        $('.add-takeEffectDate' + lineTabId).val(convertVal(data.time));
        $('.add-mixTime' + lineTabId).val(convertVal(data.mixTime));
        form.render();
    }
    function buildItemMaterial(type, index, lineId) {
        var html = convertMaterial(type);
        $('.material-body-list' + lineId).find('.add-material' + index).html(html);
        $('.material-body-list' + lineId).find('.add-storage' + index).html('<option value="">请选择ERP仓储位置</option>');
        form.render();
    }
    function buildItemControl(materialId, index_, lineId, controlStorageId) {//组装子项工控仓位、erp仓位信息
        // console.log(materialId + '   ' + index_)
        if (controlArray != null) {
            var html = '';
            var controlStorage = '';
            var controlId = -1;
            var erpStorageId = -1;
            $.each(controlArray, function (index, val) {
                if (val.lineId == lineId && val.materialId == materialId) {
                    var storageName = val.storageName;
                    if (val.controlStorage != null)
                        storageName += '[' + val.controlStorage + ']'
                    // console.log(storageName + '   ' + controlStorage + '   ' + index_)
                    html += '<option value="' + val.id + '" data-controlStorage="' + val.controlStorage + '" data-controlId="'
                        + val.controlId + '" data-storageId="'
                        + val.storageId + '">' + storageName + '</option>';
                    if (controlStorageId == null ||controlStorageId == -1) {
                        if (controlStorage == '')
                            controlStorage = val.controlStorage;
                        if (controlId == -1)
                            controlId = val.controlId;
                        if (erpStorageId == -1)
                            erpStorageId = val.id;
                    } else {
                        if (controlStorageId == val.controlId) {
                            controlStorage = val.controlStorage;
                            controlId = val.controlId;
                            erpStorageId = val.id;
                        } else {
                            if (controlStorage == '')
                                controlStorage = val.controlStorage;
                            if (controlId == -1)
                                controlId = val.controlId;
                            if (erpStorageId == -1)
                                erpStorageId = val.id;
                        }
                    }

                }
            });
            $('.material-body-list' + lineId).find('.add-storage' + index_).html(html);
            form.render();
            $('.material-body-list' + lineId).find('.add-storage' + index_).val(erpStorageId);
            $('.material-body-list' + lineId).find('.add-control' + index_).attr('data-id', controlId);
            $('.material-body-list' + lineId).find('.add-control' + index_).val(controlStorage);
            controlId = -1;
            form.render();
        } else {
            $('.material-body-list' + lineId).find('.add-control' + index_).val('暂未选择工控仓储信息');
            $('.material-body-list' + lineId).find('.add-storage' + index_).html('<option value="">请选择ERP仓储位置</option>');
            form.render();
        }
    }
    function closeTab() {
        $(".addModal").hide();
        $(".addModal input").val("");
        $(".addModal select").val("");
        $(".addModal textarea").val("");
        tid = -1;
        conId = -1;
        $.each(lineArray, function (i, v) {
            element.tabDelete('tab-line', v);
        });
        var checkBox = $(":checkbox:checked");
        $.each(checkBox, function (index, val) {
            $(val).prop('checked', false);
        });
        lineArray = new Array();
        form.render();
    }
    function saveObj(type) {//type 0 保存配比 type 1 保存并上传
        var orgId = $('.search-origin').val();
        var constructId = $.trim($('.add-construct' + lineTabId).val());//生产配比信息
        var construct = $.trim($('.add-construct' + lineTabId).find("option:selected").text());//生产配比code
        var optimize = $.trim($('.add-optimize' + lineTabId).val());//优化配比code
        var optimizeId = $.trim($('.add-optimize' + lineTabId).attr('data-optimizeid'));//优化配比code
        var mixTime = $.trim($('.add-mixTime' + lineTabId).val());//搅拌时间 level_optimize_id
        var sumDosage = $.trim($('.add-sumDosage' + lineTabId).val());//标号容设计重
        var minDosage = $.trim($('.add-minDosage' + lineTabId).val());//标号下限容设
        var maxDosage = $.trim($('.add-maxDosage' + lineTabId).val());//标号上线容重
        if (sumDosage == null || sumDosage == '')
            sumDosage = 0;
        if (minDosage == null || minDosage == '')
            minDosage = 0;
        if (maxDosage == null || maxDosage == '')
            maxDosage = 0;
        var volumeWeight = 0;//容重
        //生产线ID lineTabId 任务单ID tid 合同ID conId
        var normsList = new Array();
        var arrKey = new Array();
        var arrKey1 = new Array();
        var flag = 0;
        var tips = '';
        if (isNull(constructId)) {//如果生产配合比没有选中
            constructId = $.trim($('.add-historyConstruct' + lineTabId).find("option:selected").attr('data-constructId'));
        }
        $.each(materialArray, function (index, val) {//组装明细
            var materialType = $('.material-body-list' + lineTabId).find('.add-materialType' + val).val();
            var materialTypeText = $('.material-body-list' + lineTabId).find('.add-materialType' + val).find("option:selected").text();
            var materialId = $('.material-body-list' + lineTabId).find('.add-material' + val).val();
            var materialNorms = $('.material-body-list' + lineTabId).find('.add-material' + val).find("option:selected").text();
            var used = $('.material-body-list' + lineTabId).find('.add-realDosage' + val).val();
            var constructNum = $('.material-body-list' + lineTabId).find('.add-constructNum' + val).val();//设计用量
            var standNum = $('.material-body-list' + lineTabId).find('.add-standNum' + val).val();//砂浆用量
            var rate = $('.material-body-list' + lineTabId).find('.add-rate' + val).val();//rate含水率计算
            var dosage = $('.material-body-list' + lineTabId).find('.add-dosage' + val).val();//用量计算 storageId
            var erpStorage = $('.material-body-list' + lineTabId).find('.add-storage' + val).find("option:selected").text();//erp仓储位置
            var erpStorageId = $('.material-body-list' + lineTabId).find('.add-storage' + val).find("option:selected").attr('data-storageId');//erp仓储位置
            var controlStorage = $('.material-body-list' + lineTabId).find('.add-control' + val).val();//工控仓储位置
            var controlStorageId = $('.material-body-list' + lineTabId).find('.add-control' + val).attr('data-id');//工控仓储位置
            var validationKey =  controlStorageId + '_' + erpStorageId;
            var validationKey1 =  controlStorageId + '_' + materialId;
            if (used == null)
                used = 0;
            if (used < 0) {
                layer.msg("下标" + val + "材料设计用量不能小于0kg");
                flag = 1;
                return ;
            }
            if (used > 2000) {
                layer.msg("下标" + val + "材料设计用量不能大于2000kg");
                flag = 1;
                return ;
            }
            if (constructNum == null)
                constructNum = 0;
            if (standNum == null || standNum < 0)
                standNum = 0;
            if (rate == null)
                rate = 0;
            if (dosage == null)
                dosage = 0;
            if (materialType == null) {
                layer.msg("下标" + val + "未选择材料类型");
                flag = 1;
                return ;
            }
            if (materialId == null) {
                layer.msg("下标" + val + "未选择材料");
                flag = 1;
                return ;
            }
            if (erpStorageId == null) {
                layer.msg("下标" + val + "未选择ERP仓位信息");
                flag = 1;
                return ;
            }
            if (controlStorageId == null) {
                layer.msg("下标" + val + "未选择工控仓位信息");
                flag = 1;
                return ;
            }
            if (arrKey != null) {
                if (arrKey.includes(validationKey)) {
                    flag = 2;
                    tips += erpStorage + materialNorms + "配置信息重复   ";
                    layer.msg(materialNorms + "配置信息重复");
                    // return ;
                }
            }
            if (arrKey1 != null) {
                if (arrKey1.includes(validationKey1)) {
                    flag = 2;
                    tips += controlStorage + materialNorms + "配置信息重复   ";
                    layer.msg(materialNorms + "配置信息重复");
                    // return ;
                }
            }
            if (used != null && used > 0)
                volumeWeight = parseFloat(used) + parseFloat(volumeWeight);
            arrKey.push(validationKey);
            arrKey1.push(validationKey1);
            var obj = {orgId:orgId,materialType:materialType,materialTypeName:materialTypeText,materialId:materialId,
                materialName:materialNorms,used:used,status:0,lineId:lineTabId,erpStorageId:erpStorageId,erpStorage:erpStorage,
                controlStorageId:controlStorageId,controlStorage:controlStorage,constructNum:constructNum,standNum:standNum,rate:rate,
                dosage:dosage,isUpload:0};
            normsList.push(obj);
        });
        if (flag == 1) {
            layer.msg('存在未选择材料、工控仓位、ERP仓位、实际使用量大于2000kg或小于0');
            return;
        }
        if (flag == 2) {
            layer.msg(tips);
            return;
        }
        if (normsList == null || normsList.length == 0) {
            layer.msg('请设置配比材料子项~!');
            return;
        }
        console.log(volumeWeight + '  ' + minDosage + '   ' + maxDosage)
        var dosageFlag = 0;
        var dosageTip = '';
        if (parseInt(sumDosage) != parseInt(volumeWeight)) {
            dosageFlag = 1;
            dosageTip = '设计容重不等于实际配比容重';
        }
        if (parseInt(volumeWeight) < parseInt(minDosage)) {
            dosageFlag = 1;
            dosageTip = '实际配比容重小于标号下限容重';
        }
        if (parseInt(volumeWeight) > parseInt(maxDosage)) {
            dosageFlag = 1;
            dosageTip = '实际配比容重大于标号上限容重';
        }
        console.log(volumeWeight + '  ' + minDosage + '   ' + maxDosage)
        var options = {status:0,orgId:orgId,conId:conId,indentId:tid,labLevelConstructId:constructId,
            labLevelCode:construct,mixTime:mixTime,uploadLine:lineTabId,levelOptimizeId:optimizeId,
            list:normsList};
        if (constructId == null) {
            layer.msg("请选择施工配合比！");
            return ;
        }
        if (mixTime == null || mixTime < 10) {
            layer.msg("请设置搅拌时间且搅拌时间不能小于10秒！");
            return ;
        }
        if (dosageFlag == 0) {
            if (type == 1) {
                options['isUpload'] = 1;
                save(JSON.stringify(options), '/lab/expend-upload/save-v1', 0,'application/json');
            } else if (type == 2) {
                var uploadId = $('.line-tab' + lineTabId).find('.uploadBtns' + lineTabId).attr('data-uploadId');
                options['id'] = uploadId;
                options['lineId'] = lineTabId;
                save(options, '/lab/expend-upload/save-plc/' + uploadId, 0,'application/x-www-form-urlencoded');
            } else {
                save(JSON.stringify(options), '/lab/expend-upload/save', 0,'application/json');
            }
        } else if (dosageFlag == 1) {
            layer.confirm(dosageTip + '是否继续操作', function(index){
                // obj.del(); // 删除对应行（tr）的 DOM 结构，并更新缓存
                layer.close(index);
                if (type == 1) {
                    options['isUpload'] = 1;
                    save(JSON.stringify(options), '/lab/expend-upload/save-v1', 0,'application/json');
                } else if (type == 2) {
                    var uploadId = $('.line-tab' + lineTabId).find('.uploadBtns' + lineTabId).attr('data-uploadId');
                    options['id'] = uploadId;
                    options['lineId'] = lineTabId;
                    save(options, '/lab/expend-upload/save-plc/' + uploadId, 0,'application/x-www-form-urlencoded');
                } else {
                    save(JSON.stringify(options), '/lab/expend-upload/save', 0,'application/json');
                }
            });
        }
    }

    function calcRealSumDosage(lineId) {
        var addUsed = $('.material-body-list' + lineId).find('.add-realDosage');//实时计算实际容重
        var sumDosage = 0;
        $.each(addUsed, function (index, val) {
            var used = $(val).val();
            if (used != null)
                sumDosage = parseFloat(sumDosage) + parseFloat(used);
        });
        $('.line-tab' + lineId).find('.add-realSumDosage' + lineId).val(parseFloat(sumDosage).toFixed(1));
    }
});
function loadInitData(option, url, type, contentType) {//加载基础数据 0生产配合比 1历史配合比
    $.ajax({
        url: url,
        type: 'post',
        dataType: 'json',
        data:option,
        timeout: 30000,
        contentType: contentType,
        success: function(res) {
            if(res.code == 0 && res.data != null) {
                var data = res.data;
                if (type == 2) {//查询工控仓位信息
                    data = data.records;
                    $.each(data, function (index, val) {
                        controlArray.push(val);
                    });
                }
            }
        },
        error: function(res) {
            layer.msg("请求失败，请稍后再试！");
            return ;
        },
        complete: function(XMLHttpRequest, status) {
            if(status == 'timeout') {
                layer.msg("请求超时，请稍后再试！");
                return ;
            }
        }
    })
}